﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2021 kingerrobot
// 版权所有。 
//
// 文件名：BWmsOutOrderSummary
// 文件功能描述：
//
// 创建者：名字 (zzl)
// 时间：2021/12/21 15:56:32
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion
using KingerRobot.MexicoSailunMDC.Dao;
using Microsoft.VisualBasic;
using System;
////////using MyBatis.Common.Contracts.Constraints;

namespace KingerRobot.MexicoSailunMDC.SpiService;

public class BWmsOutOrderSummary : IWmsOutOrderSummary
{
    private readonly static IRcsLocation _RcsLocation = new BRcsLocation();
    private readonly static ITask _Task = new BTask();
    private readonly static IProdMaterial _ProdMaterial = new BProdMaterial();
    private readonly static IBakWmsOutOrderSummary _BakWmsOutOrderSummary = new BBakWmsOutOrderSummary();
    private readonly static IRcsEquip _RcsEquip = new BRcsEquip();
    private readonly static IRcsEquipCuring _RcsEquipCuring = new BRcsEquipCuring();
    private readonly static IWcsEquipLoc _WcsEquipLoc = new BWcsEquipLoc();


    public List<SummaryInCuringCount> GetTaskSummaryOccupyCount()
    {
        var db = Db.Default;

        var curingInfos = db.WcsEquipLocs.Join(db.RcsEquipCurings, f => f.EquipId, s => s.Id, (f, s) => new
        {
            EquipId = f.EquipId,
            LocId = f.LocId,
            CuringCode = s.CuringCode,
            CuringDir = s.CuringDir,
        });

        //未生成任务的
        var summaryMasters = db.WmsOutOrderMasters.Join(db.WmsOutOrderSummarys, f => f.Id, s => s.MasterId, (f, s) => new
        {
            Master = f,
            Summary = s,
        }).Where(f => f.Summary.RealCount < f.Summary.PlanCount || f.Summary.RealCount == null).ToList();

        //已经生成任务,但未送到
        //var inCuringTires = db.WcsInCuringTires.Where(f => f.Success == null).ToList();
        var inCuringTires = db.WmsOutOrderMasters.Join(db.WmsOutOrderSummarys, f => f.Id, s => s.MasterId, (f, s) => new
        {
            Master = f,
            Summary = s,
        }).Where(f => f.Summary.RealCount >= f.Summary.PlanCount).ToList();


        List<SummaryInCuringCount> list = new List<SummaryInCuringCount>();

        foreach (var curingInfo in curingInfos)
        {
            list.Add(new SummaryInCuringCount
            {
                EquipId = curingInfo.EquipId,
                LocId = curingInfo.LocId,
                CuringCode = curingInfo.CuringCode,
                CuringDir = curingInfo.CuringDir,
                SummaryCount = summaryMasters.Where(f => f.Summary.TargetLoc == curingInfo.LocId).Count(),
                // InCuringCount = inCuringTires.Where(f => f.CuringCode == curingInfo.CuringCode && f.CuringDir == curingInfo.CuringDir).Count(),
                InCuringCount = inCuringTires.Where(f => f.Summary.TargetLoc == curingInfo.LocId).Count(),

            });
        }

        return list;
    }

    public List<POWmsOutOrderSummary> GetOccupySummarys()
    {
        var db = Db.Default;

        //手工出库的
        var list1 = db.WmsOutOrderMasters.Join(db.WmsOutOrderSummarys, f => f.Id, s => s.MasterId, (f, s) => new
        {
            Master = f,
            Summary = s,
        }).Where(f => f.Summary.RealCount < f.Summary.PlanCount && f.Summary.StartLoc != null && f.Summary.StartLoc > 0).Select(f => f.Summary).ToList();

        //自动生成的
        var list2 = db.WmsOutOrderSummarys.Join(db.WcsTasks, f => f.Id, s => s.SummaryId, (f, s) => new
        {
            Task = s,
            Summary = f,
        }).Join(db.WcsTaskCmds, f => f.Task.Id, s => s.TaskId, (f, s) => new
        {
            f.Task,
            f.Summary,
            Cmd = s,
        }).Where(f => f.Cmd.CmdType == (int)EnumTaskType.Exwarehouse).Select(f => f.Summary).ToList();

        return list1.Union(list2).ToList();
    }

    [Obsolete("暂未启用", true)]
    public List<POWmsOutOrderSummary> GetOutOrderSummaryList(int type, int status)
    {
        var db = Db.Default;
        var reault = db.WmsOutOrderSummarys
            .Join(db.WmsOutOrderMasters,
            f => f.MasterId,
            s => s.Id, (f, s) => new { Master = s, Summary = f })
            .Where(t => t.Summary.FinishMode == (int)EnumCodeFinishMode.NotFinished &&
            t.Master.OrderStatus == status &&
            t.Master.OrderType == type)
            .OrderBy(t => t.Master.OrderPriority)
            .ThenBy(t => t.Master.CreateTime) // 优先级排序、时间排序
            .Select(t => t.Summary).ToList();
        return reault;
    }
    public int UpdateOrderSummaryMasterId(long summaryId, long masterId, long newmasterId)
    {
        var db = Db.Default;
        var reault = db.WmsOutOrderSummarys.Where(t => t.Id == summaryId).Update(new POWmsOutOrderSummary
        {
            SplitMasterid = masterId,
            MasterId = newmasterId,
        });
        return db.SaveChanges();




    }
    public int UpdateOrderSummaryRemark(List<long> summaryIds, string remark, bool isAppend = false)
    {
        // 优化 1
        var db = Db.Default;
        var reault = 0;
        //if (isAppend)
        //{
        foreach (var summaryId in summaryIds)
        {
            if (isAppend)
            {
                var summary = GetOutOrderSummaryById(summaryId);
                remark = (summary?.RemarkMemo ?? string.Empty) + remark;
            }
            var outSummary = db.WmsOutOrderSummarys.Where(t => t.Id == summaryId).FirstOrDefault();
            outSummary.RemarkMemo = remark;

            //if (outSummary.RemarkMemo.Length < 600)
            //{
            //    outSummary.RemarkMemo = outSummary.RemarkMemo + remark;
            //}
            //else
            //{
            //    if (outSummary.RemarkMemo.Contains("拆分") || outSummary.RemarkMemo.Contains("成功")) 
            //    {
            //        outSummary.RemarkMemo = outSummary.RemarkMemo + remark;
            //    }
            //}


            //reault = db.WmsOutOrderSummarys.Where(t => t.Id == summaryId).Update(new POWmsOutOrderSummary
            //{
            //    RemarkMemo = remark,
            //});
        }
        return db.SaveChanges();
    }

    public int UpdateOutOrderSumaryRealNum(long summaryId)
    {
        var db = Db.Default;
        var summary = GetOutOrderSummaryById(summaryId);
        if (summary is null)
        {
            return 0;
        }
        var targetLoc = summary.TargetLoc.GetValueOrDefault();
        var equip = _WcsEquipLoc.GetEquipIdByLocId(targetLoc);
        var curing = _RcsEquipCuring.GetCuringById(equip);
        var result = 0;
        if (curing?.IsCuringCall == 0)
        {
            // 需要验证 t.RealCount - 1
            var summary1 = db.WmsOutOrderSummarys.Where(t => t.Id == summaryId && t.RealCount > 0).FirstOrDefault();
            summary1.RealCount = summary.RealCount - 1;
            summary1.UpdateTime = DateTime.Now;
            result = db.SaveChanges();
        }
        return result;
    }

    public int UpdateOutOrderSumaryInventory(long summaryId, int inventory, int crnInventory, long crnId, long taskId)
    {
        var db = Db.Default;
        // 需要验证 t.RealCount - 1
        var result = db.WmsOutOrderSummarys.Where(t => t.Id == summaryId).Update(new POWmsOutOrderSummary
        {
            Inventory = inventory,
            CrnInventory = crnInventory,
            CrnId = crnId,
            TaskId = taskId,
        });

        return db.SaveChanges();

    }

    public int UpdateOutOrderSumaryTargetNum(long summaryId, int count = 1)
    {
        var db = Db.Default;
        //var summary = GetOutOrderSummaryById(summaryId);
        //if (summary is null)
        //{
        //    return 0;
        //}
        // 需要验证 t.RealCount - 1
        var summary = db.WmsOutOrderSummarys.Where(t => t.Id == summaryId).FirstOrDefault();
        summary.TargetCount = summary.TargetCount + count;
        summary.UpdateTime = DateTime.Now;
        var result = db.SaveChanges();
        return result;
    }

    public int UpdateOutOrderSumarySafe(long targetLoc, int safe)
    {
        var db = Db.Default;
        var result = 0;
        var summaries = db.WmsOutOrderSummarys.Where(t => t.TargetLoc == targetLoc).ToList();
        if (!summaries.Any())
        {
            return result;
        }
        foreach (var summary in summaries)
        {
            var task = _Task.GetTaskBySummaryId(summary.Id.GetValueOrDefault());
            if (task is not null && task.TaskType != (int)EnumTaskType.EMS && task.TaskType != (int)EnumTaskType.Abnormal)
            {
                result = db.WmsOutOrderSummarys.Where(t => t.TargetLoc == targetLoc).Update(new POWmsOutOrderSummary
                {
                    Safe = safe,
                    UpdateTime = DateTime.Now,
                });
            }
        }
        return db.SaveChanges();
    }

    public bool GetOutOrderSummaryDitchCount(long loc)
    {

        var db = Db.Default;
        var limit = db.WcsEquipLocs.Join(db.RcsEquipCurings, f => f.EquipId, s => s.Id, (f, s) => new { locId = f.LocId, ditchId = s.DitchId })
            .Where(t => t.locId == loc).Join(db.RcsEquipCuringDitchs, f => f.ditchId, s => s.Id, (f, s) => new { ditchId = f.ditchId, num = s.MaxCount })
            .FirstOrDefault();
        if (limit == null)
        {
            return false;
        }
        var reault = db.WmsOutOrderSummarys
            .Join(db.WcsEquipLocs,
            f => f.TargetLoc,
            s => s.LocId, (f, s) => new { SummaryId = f.Id, Loc = f.TargetLoc, Cur = s.EquipId })
            .Join(db.RcsEquipCurings, f => f.Cur, s => s.Id, (f, s) => new { SummaryId = f.SummaryId, Loc = f.Loc, Cur = f.Cur, DitchId = s.DitchId });
        var summaryCount = reault.Where(t => t.DitchId == limit.ditchId).Count();
        if (limit.num > summaryCount)
        {
            return true;
        }
        return false;
    }
    public bool IsCuringDitchTaskCount(long loc)
    {
        var db = Db.Default;

        // 硫化排
        var curing = db.RcsEquipCurings.Join(db.WcsEquipLocs, f => f.Id, s => s.EquipId, (f, s) => new
        {
            Curing = f,
            Loc = s,
        }).Where(t => t.Loc.LocId == loc).FirstOrDefault();

        var ditchId = curing?.Curing?.DitchId ?? 0;

        // 是否满足硫化排任务数
        var maxCount = GetCuringDitchTaskCount(ditchId);
        var result = db.RcsEquipCuringDitchs.Where(t => t.Id == ditchId && t.MaxCount > maxCount).FirstOrDefault();
        return result != null;
    }

    private int GetCuringDitchTaskCount(long ditchId)
    {
        if (ditchId == 0) return 0;

        var db = Db.Default;

        // 未结束硫化排任务
        var taskCount = db.WmsOutOrderSummarys.Where(t => t.FinishMode == (int)EnumFinishMode.NotFinished)
            .Join(db.WcsTasks, f => f.Id, s => s.SummaryId, (f, s) => new
            {
                Summary = f,
                Task = s,
            }).Join(db.WcsEquipLocs, f => f.Summary.TargetLoc, s => s.LocId, (f, s) => new
            {
                f.Summary,
                f.Task,
                Loc = s,
            }).Join(db.RcsEquipCurings, f => f.Loc.EquipId, s => s.Id, (f, s) => new
            {
                DitchId = s.DitchId,
                TaskNo = f.Task.TaskNo,
            }).Where(t => t.DitchId == ditchId).GroupBy(t => t.DitchId).Select(t => new
            {
                DitchId = t.Key.Value,
                Count = t.Count(),
            }).FirstOrDefault(); //.Where(t => t.DitchId == ditchId).FirstOrDefault();

        return taskCount?.Count ?? 0;

    }



    public POWmsOutOrderSummary GetDirectDeliveryOutOrderSummary(long locId, long materialId)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Join(db.WmsOutOrderMasters, f => f.MasterId, s => s.Id, (f, s) => new
        {
            Summary = f,
            Master = s,
            //}).Where(t => t.Master.DirectLoc == locId && t.Master.DirectDelivery == 1 && t.Summary.MaterialId == materialId && t.Summary.PlanCount > t.Summary.RealCount)
        }).Where(t => t.Master.DirectDelivery == 1 && t.Summary.MaterialId == materialId && t.Summary.PlanCount > t.Summary.RealCount)
        .OrderBy(t => t.Master.CreateTime)
        .Select(t => t.Summary)
        .FirstOrDefault();
        return result;
    }

    public List<POWmsOutOrderSummary> GetOutOrderSummaryNoTaskList(int?[] type)
    {
        var db = Db.Default;

        var reault = db.WmsOutOrderSummarys
            .Join(db.WmsOutOrderMasters, // 这里关联用到 OrderPriority （优先级）
            f => f.MasterId,
            s => s.Id, (f, s) => new { Master = s, Summary = f })
            .Where(t => t.Summary.FinishMode == (int)EnumCodeFinishMode.NotFinished &&
            t.Summary.PlanCount > t.Summary.RealCount && type.Contains(t.Master.OrderType))
            .OrderBy(t => t.Master.OrderPriority)
            .ThenBy(t => t.Master.CreateTime) // 优先级排序、时间排序
            .Select(t => t.Summary).ToList();
        return reault;
    }

    public List<POWmsOutOrderSummary> GetOutOrderSummaryHasTaskList()
    {
        var db = Db.Default;
        var reault = db.WmsOutOrderSummarys.Where(t => t.RealCount == 1).ToList();
        return reault;
    }


    public List<OrderSummaryGroupyMaster> GetNoTaskLocOrderSummaryGroup(int type)
    {
        var db = Db.Default;
        var summaries = db.WmsOutOrderSummarys
            .Join(db.WmsOutOrderMasters, // 这里关联用到 OrderPriority （优先级）
            f => f.MasterId,
            s => s.Id, (f, s) => new { Master = s, Summary = f })
            .Where(t => t.Summary.FinishMode == (int)EnumCodeFinishMode.NotFinished &&
            t.Summary.PlanCount > t.Summary.RealCount && t.Master.OrderType == type)
            .OrderBy(t => t.Master.OrderPriority)
            .ThenBy(t => t.Master.CreateTime) // 优先级排序、时间排序
            .Select(t => new { Summary = t.Summary, OrderPriority = t.Master.OrderPriority }).ToList();

        var result = summaries
            .GroupBy(t => new { t.Summary.MasterId })
            .Select(t => new OrderSummaryGroupyMaster
            {
                MasterId = t.Key.MasterId.Value,
                CreateTime = t.FirstOrDefault()?.Summary?.CreateTime,
                Count = t.Count(),
                POWmsOutOrderSummaries = t.Select(s => s.Summary).ToList(),
                OrderPriority = t.FirstOrDefault()?.OrderPriority.GetValueOrDefault()
            }).ToList();

        return result;
    }


    public List<OrderSummaryGroupyMaster> GetNoTaskOrderSummaryGroup(int type)
    {
        var db = Db.Default;
        var summaries = db.WmsOutOrderSummarys
            .Join(db.WmsOutOrderMasters, // 这里关联用到 OrderPriority （优先级）
            f => f.MasterId,
            s => s.Id, (f, s) => new { Master = s, Summary = f })
            .Join(db.WcsEquipLocs, f => f.Summary.TargetLoc, s => s.LocId, (f, s) => new
            {
                f.Master,
                f.Summary,
                EquipLocs = s,
            })
            .Join(db.RcsEquipCurings, f => f.EquipLocs.EquipId, s => s.Id, (f, s) => new
            {
                f.Master,
                f.Summary,
                f.EquipLocs,
                Curings = s,
            })
            .Where(t => t.Summary.FinishMode == (int)EnumCodeFinishMode.NotFinished &&
            t.Summary.PlanCount > t.Summary.RealCount && t.Master.OrderType == type)
            .OrderBy(t => t.Master.OrderPriority)
            .ThenBy(t => t.Master.CreateTime) // 优先级排序、时间排序
            .Select(t => new { Summary = t.Summary, OrderPriority = t.Master.OrderPriority, Curings = t.Curings }).ToList();

        var result = summaries
            .GroupBy(t => new { t.Summary.MasterId })
            .Select(t => new OrderSummaryGroupyMaster
            {
                MasterId = t.Key.MasterId.Value,
                CreateTime = t.FirstOrDefault()?.Summary?.CreateTime,
                Count = t.Count(),
                DitchId = t.FirstOrDefault()?.Curings?.DitchId ?? 0,
                POWmsOutOrderSummaries = t.Select(s => s.Summary).ToList(),
                OrderPriority = t.FirstOrDefault()?.OrderPriority.GetValueOrDefault(),
                OrderType = type,
            }).ToList();

        return result;
    }

    public POWmsOutOrderSummary GetOutOrderSummaryByTargetLocId(long locId)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.TargetLoc == locId).FirstOrDefault();
        return result;
    }
    public POWmsOutOrderSummary GetOutOrderSummaryByStartLocId(long locId)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.StartLoc == locId).FirstOrDefault();
        return result;
    }

    public List<POWmsOutOrderSummary> GetOutOrderSummarysByTargetLocId(long locId)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.TargetLoc == locId).ToList();
        return result;
    }
    private List<POWmsOutOrderSummary> GetOutOrderSummarysByTargetLocIds(List<long> locIds)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => locIds.Contains(t.TargetLoc.GetValueOrDefault())).ToList();
        return result;
    }

    private List<POWmsOutOrderSummary> GetOutOrderSummarysByCuringsCodes(string curingCode)
    {
        var db = Db.Default;
        // 查找硫化机
        var result = db.RcsEquipCurings
        .Join(db.RcsEquips, f => f.Id, s => s.Id, (f, s) => new { Curing = f, Equip = s })
        .Where(t => t.Equip.EquipEnable == 1 && t.Equip.ErrCode == 0 && t.Curing.UseFlag == 1 && t.Curing.CuringCode == curingCode)
        .Join(db.WmsOutOrderSummarys, f => f.Curing.LocId, s => s.TargetLoc, (f, s) => s)
        .ToList();
        return result;
    }
    public List<POWmsOutOrderSummary> GetOutOrderSummaryByMasterId(long masterId)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.MasterId == masterId).ToList();
        return result;
    }
    public List<POWmsOutOrderSummary> GetOutOrderSummaryNoTaskByMaterialId(long materialId)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.MaterialId == materialId && t.PlanCount > t.RealCount).ToList();
        return result;
    }
    public bool IsOutOrderSummaryByMasterId(long masterId) => GetOutOrderSummaryByMasterId(masterId).Count() > 0;
    public POWmsOutOrderSummary GetOutOrderSummaryById(long id)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.Id == id).FirstOrDefault();
        return result;
    }
    public POBakWmsOutOrderSummary GetBakOutOrderSummaryById(long id)
    {
        var db = Db.Default;
        var result = db.BakWmsOutOrderSummarys.Where(t => t.Id == id).FirstOrDefault();
        return result;
    }
    public bool IsOutOrderSummaryByLocId(long locId) => GetOutOrderSummaryByTargetLocId(locId) is not null;



    public bool IsOutOrderSummaryPairByLocId(long locId)
    {
        var equip = _WcsEquipLoc.GetEquipIdByLocId(locId);
        var curing = _RcsEquipCuring.GetCuringById(equip);
        var curingCode = curing?.CuringCode;

        //var curingIds = _RcsEquipCuring.GetEquipCuringsByCode(curingCode).Select(t => t.Id).ToList();
        //var locIds = _RcsLocation.GetLocationsByLocIds(curingIds).Select(t => t.Id.GetValueOrDefault()).ToList();
        //var summarys = GetOutOrderSummarysByTargetLocIds(locIds);

        var summarys = GetOutOrderSummarysByCuringsCodes(curingCode);
        if (summarys.Count == 2)
        {
            return true;
        }

        return false;
    }
    public int UpdateSummaryLocAndRealCount(long? id, long? startLoc, int count = 0, string remark = "")
    {
        // TODO t.RealCount + count 需要验证
        var db = Db.Default;
        var result = 0;
        var summary = db.WmsOutOrderSummarys.Where(t => t.Id == id && t.PlanCount > t.RealCount).FirstOrDefault();
        if (summary is not null)
        {
            summary.StartLoc = startLoc;
            summary.RealCount = summary.RealCount + count;
            summary.UpdateTime = DateTime.Now;
            summary.RemarkMemo = remark;
            result = db.SaveChanges();
        }
        return result;
    }

    public int RollBackSummaryLocAndRealCount(long? id, string remark, int count = 0)
    {
        var db = Db.Default;
        var summary = GetOutOrderSummaryById(id ?? 0);
        var qty = summary.RealCount > 0 ? summary.RealCount - count : 0;

        var datetime = DateTime.Now;
        var remarkMome = $"【{remark}{datetime}】 | {summary.RemarkMemo}";
        var subStr = remarkMome.Substring(0, (remarkMome.Length < 900 ? remarkMome.Length : 900));

        var result = db.WmsOutOrderSummarys.Where(t => t.Id == id)
            .Update(new POWmsOutOrderSummary
            {
                StartLoc = null,
                RealCount = qty,
                UpdateTime = datetime,
                RemarkMemo = subStr
            });
        return db.SaveChanges();
    }

    public int ReRequestSummary(long summaryId)
    {
        // TODO 需要验证 t.RealCount - 1
        var db = Db.Default;

        var summary = db.WmsOutOrderSummarys.Where(t => t.Id == summaryId).FirstOrDefault();
        summary.StartLoc = null;
        summary.RealCount = summary.RealCount - 1;
        summary.UpdateTime = DateTime.Now;

        return db.SaveChanges();
    }
    public int BakUpdateAndDeleteOutOrderSummary(POWmsOutOrderSummary summary, string remark = "")
    {
        if (summary == null)
        {
            return 0;
        }
        var id = summary.Id.GetValueOrDefault();
        // 修改备注
        var result = UpdateOrderSummaryRemark(new() { id }, $"{remark} | {summary.RemarkMemo}");

        // 备份
        result += BakOutOderSummary(summary);

        // 删除
        result += DeleteOutOderSummary(id);

        return result;
    }
    private int DeleteOutOderSummary(long? id)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.Id == id).Delete();
        return result;
    }
    private int BakOutOderSummary(POWmsOutOrderSummary wmsOutOrderSummary)
    {
        var db = Db.Default;
        var result = 0;


        if (_BakWmsOutOrderSummary.GetBakWmsOutOrderSummaryById(wmsOutOrderSummary.Id.GetValueOrDefault()) != null)
        {
            return 0;
        }

        try
        {
            wmsOutOrderSummary.TargetCount = 1;
            wmsOutOrderSummary.FinishMode = (int)EnumCodeFinishMode.NormalEnd;
            wmsOutOrderSummary.FinishTime = DateTime.Now;
            result = db.BakWmsOutOrderSummarys.CopyFrom(wmsOutOrderSummary);
        }
        catch (Exception ex)
        {
            WriteLog(ex.ToString());
        };
        return result;
    }

    public int BakAndDeleteOutOrderSummary(long id)
    {
        //WriteLog($"记录出库单id，id:{id}", true);
        var summary = GetOutOrderSummaryById(id);
        if (summary == null)
        {
            return 0;
        }

        var result = UpdateOutOrderSumaryTargetNum(id);

        //WriteLog($"开始执行出库完成1，summary.PlanCount{summary.PlanCount}---{summary.TargetCount + 1}", true);
        // 计划和实际完成数量一致。
        if (summary.PlanCount <= (summary.TargetCount + 1))
        {
            //WriteLog($"开始执行出库完成操作，开始修改出库单状态1记录参数 id-{id}，status-{(int)EnumCodeFinishMode.NormalEnd}", true);
            result += UpdateOutOrderSummaryFinish(id, (int)EnumCodeFinishMode.NormalEnd);
            //WriteLog($"开始执行出库完成操作，完成修改出库单状态2，修改结果为:{result}", true);

            summary = GetOutOrderSummaryById(id);
            result += BakOutOderSummary(summary);

            result += DeleteOutOderSummary(id);
        }

        return result;
    }


    public int UpdateOutOrderSummaryAllFinish(long masterId, int finishMode)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.MasterId == masterId).Update(new POWmsOutOrderSummary
        {
            FinishMode = finishMode,
            FinishTime = DateTime.Now,
        });
        return db.SaveChanges();
    }


    public int UpdateOutOrderSummaryFinish(long summaryId, int finishMode)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => t.Id == summaryId).Update(new POWmsOutOrderSummary
        {
            FinishMode = finishMode,
            FinishTime = DateTime.Now,
        });
        return db.SaveChanges();
    }
    public int AddOutOrderSummaryList(List<OutOrderSummary> outOrderSummaries)
    {
        if (outOrderSummaries is null || outOrderSummaries.Count == 0)
        {
            return 0;
        }
        var specs = outOrderSummaries.Select(t => t.Spec).Distinct().ToList();
        var materials = _ProdMaterial.GetMaterialBySpecs(specs);
        if (materials.Count != specs.Count)
        {
            WriteLog($"请料物料Spec 不存在");
            return 0;
        }
        long summaryId;
        int num;
        foreach (var item in outOrderSummaries)
        {
            // 修改货位为空
            _RcsLocation.UpdateLocationNoGood(item.TargetLoc);

            var equip = _RcsEquip.GetRcsEquipByLocId(item.TargetLoc);
            if (equip is null)
            {
                continue;
            }
            // 添加订单信息
            var material = materials.Where(t => t.Spec == item.Spec).FirstOrDefault();
            summaryId = XID.Nextval;
            num = AddOutOrderSummary(new()
            {
                Id = summaryId,
                MesDetailId = item.MidId,
                MasterId = item.MasterId,
                SummaryIndex = item.SummaryIndex,
                RotateAngle = item.RotateAngle,
                TargetLoc = item.TargetLoc,
                MaterialId = material?.Id,
                SkuBatch = item.SkuBatch,
                Serno = item.Serno,
                Stock = item.Stock,
                PlanCount = item.PlanCount,
                StartLoc = item.StartLoc,

                TooltipMemo = item.Remark,
            });
            if (num > 0)
            {
                //回写订单从表id 用于对接MES中间表、WebService接口
                item.SummaryId = summaryId;
            }
        }

        return 1;
    }
    public int AddOutOrderSummaryListByLoc(List<POWmsOutOrderSummary> WmsOutOrderSummaries)
    {
        if (WmsOutOrderSummaries is null || WmsOutOrderSummaries.Count == 0)
        {
            return 0;
        }
        var db = Db.Default;
        WmsOutOrderSummaries.ForEach(item =>
        {
            item.Id = XID.Nextval;
            db.WmsOutOrderSummarys.Insert(item);
        });

        return 1;
    }
    /// <summary>
    /// 保存出库单-从表
    /// </summary>
    /// <param name="pOWmsOutOrderSummary"></param>
    /// <returns></returns>
    public int AddOutOrderSummary(POWmsOutOrderSummary pOWmsOutOrderSummary)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Insert(new POWmsOutOrderSummary()
        {
            Id = pOWmsOutOrderSummary.Id,
            MasterId = pOWmsOutOrderSummary.MasterId,
            SummaryIndex = pOWmsOutOrderSummary.SummaryIndex,
            TargetLoc = pOWmsOutOrderSummary.TargetLoc,
            MaterialId = pOWmsOutOrderSummary.MaterialId,
            SkuBatch = pOWmsOutOrderSummary.SkuBatch,
            Serno = pOWmsOutOrderSummary.Serno,
            Stock = pOWmsOutOrderSummary.Stock,
            PlanCount = pOWmsOutOrderSummary.PlanCount,
            StartLoc = pOWmsOutOrderSummary.StartLoc,
            MesDetailId = pOWmsOutOrderSummary.MesDetailId,
            TooltipMemo = pOWmsOutOrderSummary.TooltipMemo,
        });
        return result;
    }

    public bool IsMateiralSameSummary(List<long?> ids)
    {
        var db = Db.Default;
        var summaries = db.WmsOutOrderSummarys.Where(t => ids.Contains(t.TargetLoc) && t.RealCount > 0).ToList();

        if (summaries.Count <= 1)
        {
            return false;
        }
        var first = summaries.FirstOrDefault()?.MaterialId;
        var second = summaries.LastOrDefault()?.MaterialId;

        if (first == second)
        {
            return true;
        }

        return false;
    }

    public List<POWmsOutOrderSummary> GetOutOrderSummaryByIds(List<long?> ids)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.Where(t => ids.Contains(t.Id)).ToList();
        return result;
    }


    public int BakAndDeleteOutOrderSummaryByMasterId(long masterId, string remark)
    {
        //WriteLog($"")
        var summaryList = GetOutOrderSummaryByMasterId(masterId);
        var result = 0;
        foreach (var summary in summaryList)
        {
            summary.RemarkMemo = remark;
            result += BakOutOderSummary(summary);
            result += DeleteOutOderSummary(summary.Id ?? 0);
            //WriteLog()
        }

        return result;


    }

    public int UpdateSummaryByTcmNoAndSpec(string TcmNo, string Spec)
    {
        var result = 0;
        WriteLog($"换膜删除{TcmNo}-111,{Spec}", true);


        var curings = _RcsEquipCuring.GetEquipCuringsByCode(TcmNo);
        WriteLog($"换膜删除{TcmNo}-1112", true);
        //暂时判断一个膜 因为不会请不同料 也不会单模请料
        if (curings is not null && curings.Count == 2)
        {
            WriteLog($"换膜删除{TcmNo}-222", true);
            var curingL = curings.Where(t => t.CuringDir == "L").FirstOrDefault()?.LocId ?? 0;
            var curingR = curings.Where(t => t.CuringDir == "R").FirstOrDefault()?.LocId ?? 0;
            if (curingL == 0 || curingR == 0)
            {
                WriteLog($"换膜删除{TcmNo}-333", true);
                return result;
            }
            var newMaterialId = _ProdMaterial.GetMaterialByCode(Spec)?.Id ?? 0;
            WriteLog($"换膜删除{TcmNo}-444", true);
            if (newMaterialId == 0)
            {
                WriteLog($"换膜删除{TcmNo}-555", true);
                return result;
            }

            //查询当前硫化是否有请料单
            var summaryL = GetOutOrderSummaryByTargetLocId(curingL);
            var summaryR = GetOutOrderSummaryByTargetLocId(curingR);
            WriteLog($"换膜删除{TcmNo}-666", true);
            if (summaryL is not null && summaryR is not null && summaryL.MaterialId != newMaterialId && summaryR.MaterialId != newMaterialId)
            {
                WriteLog($"换膜删除{TcmNo}-777", true);
                if (summaryL.RealCount == 0 && summaryR.RealCount == 0)
                {
                    WriteLog($"换膜删除{TcmNo}-888", true);
                    BakAndDeleteOutOrderSummaryByMasterId(summaryL.MasterId ?? 0, $"换膜删除,原物料{summaryL.MaterialId},现物料{newMaterialId}");
                    result = 1;
                }
            }
        }
        WriteLog($"换膜删除{TcmNo}-999", true);
        return result;
    }
}
